<?php

namespace App\Http\Controllers\Front;

use App\Model\Articles;
use App\Model\Cards;
use App\Model\UserMarketing;
use App\Model\UserTemplate;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ShareController extends Controller
{
    public function index()
    {
        try {
            DB::beginTransaction();
            //插入分享记录
            DB::table('share')->insert([
                'user_id' => Auth::check()?Auth::id():0,
                'target_id' => request('id'),
                'type' => request('type'),
                'created_at' => Carbon::now()
            ]);
            $this->incrementShareCount(request('id'), request('type'));
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error();
        }
        return $this->success();
    }

    /**
     * @param int $id 目标id
     * @param int $type 类型 1文章2个人网页3
     */
    private function incrementShareCount($id, $type)
    {
        switch ($type){
            case 1:
                Articles::find($id)->increment('share_num');
                break;
            case 2:
                UserTemplate::find($id)->increment('share');
                break;
            case 3:
                Cards::find($id)->increment('share');
                break;
            case 4:
                UserMarketing::find($id)->increment('share');
                break;
        }
    }
}
